<template>
  <div class="tree-container">
    <div class="tree-content" :style="`width: ${treeWidth}px`">

      <!-- 车辆树搜索盒 -->
      <div class="tree-search-box" v-show="treeWidth">
        <div class="search-li">
          <el-input class="search-enter" v-model="queryParams.queryParam" clearable placeholder="请输入车牌号 / 设备号 / 自编号" />
          <img class="search-img" src="@/assets/images/safety/search.png" @click="changeCarTree" />
        </div>
        <div class="search-li">
          <el-select class="search-enter" v-model="queryParams.status" placeholder="请选择车辆类型" @change="changeCarTree">
            <el-option v-for="item in carTypeOptions" :key="item.value" :label="item.label + '【' + item.number + '】'"
              :value="item.value" />
          </el-select>
          <!-- 车辆查询选项配置弹出框 -->
          <el-popover placement="right" :width="352" :visible="settingVisible">
            <template #reference>
              <img class="search-img" src="@/assets/images/safety/setting.png" @click="settingVisible = true" />
            </template>
            <el-form ref="settingFormRef" label-position="top" label-width="100px" :model="form">
              <el-form-item label="页面全局设置">
                <el-checkbox-group v-model="form.global">
                  <el-checkbox label="只监联网联控车辆" name="gloab" value="" />
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="车辆选择列表">
                <el-checkbox-group v-model="form.groupShow">
                  <el-checkbox label="车队显示" name="car" />
                  <el-checkbox label="线路显示" name="line" />
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="列表分类">
                <el-checkbox-group v-model="form.listCate">
                  <el-checkbox label="全部车辆" name="1" disabled />
                  <el-checkbox label="在线车辆" name="2" />
                  <el-checkbox label="离线车辆" name="3" />
                  <el-checkbox label="关注车辆" name="4" />
                  <el-checkbox label="停运车辆" name="5" />
                  <el-checkbox label="行驶车辆" name="6" />
                  <el-checkbox label="熄火车辆" name="7" />
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="车辆显示">
                <el-checkbox-group v-model="form.carShow">
                  <el-checkbox label="车牌" name="1" />
                  <el-checkbox label="自编号" name="2" />
                  <el-checkbox label="车辆类型" name="3" />
                  <el-checkbox label="驾驶员姓名" name="4" />
                  <el-checkbox label="速度" name="5" />
                  <el-checkbox label="所在区域" name="6" />
                  <el-checkbox label="设备编号" name="7" />
                </el-checkbox-group>
              </el-form-item>
              <el-form-item>
                <el-button :loading="buttonLoading" size="small" type="primary" @click="submitSettingForm">
                  保存
                </el-button>
                <el-button size="small" @click="settingVisible = false">关闭</el-button>
              </el-form-item>
            </el-form>
          </el-popover>
        </div>
      </div>

      <!-- 车辆树 -->
      <div class="ztree-box" :style="`min-height: ${ztreeHeight}px; max-height: ${ztreeHeight}px`">
        <div class="ztree vue-giant-tree" :id="ztreeData.ztreeId"></div>
      </div>

      <!-- 车辆树右键弹框 -->
      <v-contextmenu ref="contextmenu" theme="bright">
        <v-contextmenu-item
          v-if="ztreeData.rightClickType == 'dept' || ztreeData.rightClickType == 'fleet' || ztreeData.rightClickType == 'route'"
          @click="collectVehicle">收藏
        </v-contextmenu-item>
        <v-contextmenu-item
          v-if="ztreeData.rightClickType == 'dept' || ztreeData.rightClickType == 'fleet' || ztreeData.rightClickType == 'route'"
          @click="deleteCollectVehicle">取消收藏
        </v-contextmenu-item>
        <v-contextmenu-item v-if="ztreeData.rightClickType == 'vehicle'"
          v-on="{ click: ztreeData.rightClickCarData.collectState != 1 ? collectVehicle : deleteCollectVehicle }">{{
            ztreeData.rightClickCarData.collectState != 1 ? '收藏' : '取消收藏' }}
        </v-contextmenu-item>
        <v-contextmenu-item v-if="ztreeData.rightClickType == 'vehicle'" @click="carRoll">车辆点名</v-contextmenu-item>
        <v-contextmenu-item v-if="ztreeData.rightClickType == 'vehicle'" @click="historyTrack">轨迹跟踪</v-contextmenu-item>
        <v-contextmenu-item v-if="ztreeData.rightClickType == 'vehicle'" @click="liveVideo">实时视频</v-contextmenu-item>
        <v-contextmenu-item v-if="ztreeData.rightClickType == 'vehicle'" @click="videoHistory">视频回放</v-contextmenu-item>
        <v-contextmenu-item
          v-if="ztreeData.rightClickType == 'vehicle' || ztreeData.rightClickType == 'dept' || ztreeData.rightClickType == 'fleet' || ztreeData.rightClickType == 'route'"
          @click="sms">短信下发
        </v-contextmenu-item>
        <v-contextmenu-item
          v-if="ztreeData.rightClickType == 'vehicle' || ztreeData.rightClickType == 'dept' || ztreeData.rightClickType == 'fleet' || ztreeData.rightClickType == 'route'"
          @click="voice">语音对讲
        </v-contextmenu-item>
        <v-contextmenu-item
          v-if="ztreeData.rightClickType == 'vehicle' || ztreeData.rightClickType == 'dept' || ztreeData.rightClickType == 'fleet' || ztreeData.rightClickType == 'route'"
          @click="takePhoto">拍摄照片
        </v-contextmenu-item>
        <v-contextmenu-item v-if="ztreeData.rightClickType == 'vehicle'" @click="terminalRead">终端信息读取</v-contextmenu-item>
        <v-contextmenu-item
          v-if="ztreeData.rightClickType == 'vehicle' || ztreeData.rightClickType == 'dept' || ztreeData.rightClickType == 'fleet' || ztreeData.rightClickType == 'route'"
          @click="terminalSetting">终端参数设置
        </v-contextmenu-item>
      </v-contextmenu>


      <!-- 车辆信息弹出盒 -->
      <div class="eject-box" v-show="treeWidth">
        <carEjectBox @handleTreeHeight="changeTreeHeight" :vehicle-data="currentSelectVehicleData" />
      </div>
    </div>

    <div class="scale-btn" :class="{ 'scale-open': treeWidth }">
      <img :src="treeWidth ? scaleBtn : scale2Btn" @click="toggleTreeWidth">
    </div>
  </div>
</template>

<script setup name="carTree">
import carEjectBox from '../carEjectBox/index.vue'
import { computed, nextTick, reactive, toRefs, watch } from 'vue';
import useVehicleStore from '@/store/modules/vehicle'
import useSatetyMapStore from '@/store/modules/safetyMap'
import { detaildPageSetting, addPageSetting, updatePageSetting } from '@/api/basic/userPageSetting.js'
import "@ztree/ztree_v3/js/jquery.ztree.all";
import { vehicleTree, vehicleTreeList, vehicleDetail } from '@/api/safety/vehicle.js'
import { addCollectVehicle, delCollectVehicle } from '@/api/safety/collectVehicle.js'
const emits = defineEmits(['onAsyncError', 'onAsyncSuccess', 'onClick', 'onCheck']);

import scaleBtn from '@/assets/images/safety/scale.png'
import scale2Btn from '@/assets/images/safety/scale.png'

const { proxy } = getCurrentInstance();
const { basic_vehicle_type } = proxy.useDict('basic_vehicle_type');

const treeWidth = ref(290); //车辆树content宽度

//车辆树结构ztree高度
const ztreeHeight = computed(() => {
  return safeMapStore.ztreeHeight
})

//显示隐藏车辆树框
function toggleTreeWidth() {
  if (treeWidth.value == 0) {
    treeWidth.value = 290;
  } else {
    treeWidth.value = 0;
    settingVisible.value = false;
  }
}

//显示隐藏车辆信息状态框
function changeTreeHeight(e) {
  safeMapStore.setTreeEjectHeight(e)
  safeMapStore.setZtreeHeight(e == 259 ? 480 : 707)
}

//车辆类型配置初始参数
const carTypeOptionConfig = reactive([
  {
    label: '全部车辆',
    value: 1,
    number: 0,
  },
  {
    label: '在线车辆',
    value: 2,
    number: 0,
  },
  {
    label: '离线车辆',
    value: 3,
    number: 0,
  },
  {
    label: '关注车辆',
    value: 4,
    number: 0,
  },
  {
    label: '停运车辆',
    value: 5,
    number: 0,
  },
  {
    label: '行驶车辆',
    value: 6,
    number: 0,
  },
  {
    label: '熄火车辆',
    value: 7,
    number: 0,
  },
])
const carTypeOptions = computed(() => {
  return carTypeOptionConfig.filter((item) => {
    return ConfigSetting.value.listCate.includes(item.label)
  })
})

//获取车辆类型关联的数量信息
const store = useVehicleStore()
const totalInfo = ref({})

carsTotal()
function carsTotal() {
  store.vehicleCollect().then(res => {
    totalInfo.value = res
    carTypeOptionConfig.map((item) => {
      switch (item.value) {
        case 1:
          item.number = res.all
          break;
        case 2:
          item.number = res.online
          break;
        case 3:
          item.number = res.offline
          break;
        case 4:
          item.number = res.collect
          break;
        case 5:
          item.number = res.outage
          break;
        case 6:
          item.number = res.run
          break;
        case 7:
          item.number = res.stall
          break;
      }
      return item
    })
  })
}

const data = reactive({
  //车辆选项配置
  form: {
    global: ["只监联网联控车辆"],
    groupShow: [],
    listCate: ['全部车辆', '在线车辆', '离线车辆', '关注车辆'],
    carShow: ['车牌'],
  },

  queryParams: {
    netState: 0, //0禁用 1启用
    fleet: 0, //是否显示车队
    route: 0, //是否显示线路
    status: 1, //车辆分类 1全部车辆 2在线车辆 3离线车辆 4关注车辆 5停运车辆 6行驶车辆 7停火车辆
    queryParam: ''
  }
})
const { queryParams, form } = toRefs(data);

//设置配置项框 可见状态以及保存按钮
const settingVisible = ref(false)
const buttonLoading = ref(false)

//车辆选项配置
const ConfigSetting = ref(form.value);
const configForm = ref();
var configKey = 'treeConfigPage';
getConfig();
async function getConfig() {
  let config = await detaildPageSetting(configKey)
  // console.log('config', config)
  if (config.data != null) {
    configForm.value = config.data
    ConfigSetting.value = JSON.parse(config.data.content)
    form.value = JSON.parse(config.data.content)
  } else {
    ConfigSetting.value = data.form
  }
  searchCar()
}

//保存车辆选项配置
function submitSettingForm() {
  proxy.$refs["settingFormRef"].validate(valid => {
    // console.log('settingFormRef', form.value)
    if (valid) {
      buttonLoading.value = true;
      let params = {
        page: configKey,
        content: JSON.stringify(form.value)
      }

      if (typeof configForm.value.id == 'undefined') {
        addPageSetting(params).then(res => {
          proxy.$modal.msgSuccess("添加成功");
          settingVisible.value = false
          ConfigSetting.value = JSON.parse(JSON.stringify(form.value))
          searchCar()
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        params.id = configForm.value.id;
        updatePageSetting(params).then(res => {
          proxy.$modal.msgSuccess("保存成功");
          settingVisible.value = false
          ConfigSetting.value = JSON.parse(JSON.stringify(form.value))
          searchCar()
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  })
}

//车辆类型选择或者输入input框关键词改变事件
function changeCarTree() {
  searchCar()
}

//ztree树配置
const ztreeData = reactive({
  ztreeId: "ztree_" + parseInt(Math.random() * 1e10),
  rightClickType: '',
  rightClickCarData: [], //右键点击的车辆数据

  ztreeObj: null,
  selectedCarIds: [],
  list: [
    { id: 1, pid: 0, name: "全局", open: true },
    { id: 11, pid: 1, name: "随意勾选 1-1", open: true },
    { id: 111, pid: 11, name: "随意勾选 1-1-1" },
    { id: 112, pid: 11, name: "随意勾选 1-1-2" },
    { id: 12, pid: 1, name: "随意勾选 1-2", open: true },
    { id: 121, pid: 12, name: "随意勾选 1-2-1" },
    { id: 122, pid: 12, name: "随意勾选 1-2-2" },
    { id: 2, pid: 0, name: "随意勾选 2", checked: true, open: true },
    { id: 21, pid: 2, name: "随意勾选 2-1" },
    { id: 22, pid: 2, name: "渝A35799(0785266)[危险品运输车]  王有明   32km/s  涪陵区  （ID556987741）", type: 'vehicle', open: true, diy: 'zc', iconSkin: "icon04" }, // icon: offlineImg 
    { id: 221, pid: 22, name: "随意勾选 2-2-1", checked: true },
    { id: 222, pid: 22, name: "随意勾选 2-2-2", nocheck: true },
    { id: 23, pid: 2, name: "随意勾选 2-3" },
  ],
  ztreeSetting: {
    view: {
      showIcon: false, //默认隐藏Icon
    },
    callback: {
      onCheck: (...arg) => {
        checkChange(...arg)
        // emits("onCheck", ...arg);
      },
      onClick: (...arg) => {
        nodeClick(...arg)
        // emits("onClick", ...arg);
      },
      onCollapse: (...arg) => {
        emits("onCollapse", ...arg);
      },
      onDblClick: (...arg) => {
        emits("onDblClick", ...arg);
      },
      onDrag: (...arg) => {
        emits("onDrag", ...arg);
      },
      onDragMove: (...arg) => {
        emits("onDragMove", ...arg);
      },
      onDrop: (...arg) => {
        emits("onDrop", ...arg);
      },
      onExpand: (...arg) => {
        emits("onExpand", ...arg);
      },
      onMouseDown: (...arg) => {
        emits("onMouseDown", ...arg);
      },
      onMouseUp: (...arg) => {
        emits("onMouseUp", ...arg);
      },
      onRightClick: (...arg) => {
        nodeContextmenu(...arg)
        // emits("onRightClick", ...arg);
      },
      beforeMouseDown: (...arg) => {
        contextmenu.value.hide()
      }
    }
  }
})

const safeMapStore = useSatetyMapStore();

//所有车辆数据和ids的集合
var allVehicleDatas = {};
var allVehicleIds = [];

//查询车辆树
function searchCar(init = true) {
  // console.log('init', init)
  queryParams.value.netState = ConfigSetting.value.global.includes('只监联网联控车辆') ? 1 : 0;
  queryParams.value.fleet = ConfigSetting.value.groupShow.includes('车队显示') ? 1 : 0;
  queryParams.value.route = ConfigSetting.value.groupShow.includes('线路显示') ? 1 : 0;

  vehicleTree(queryParams.value).then(res => {
    allVehicleDatas = {};
    allVehicleIds = [];
    _rebuildDatas(res.data)
    console.log('ztreeData.list', res.data)
    ztreeData.list = res.data
    safeMapStore.setDefaultAllVehicleIds(allVehicleIds)
    init == true ? initTree() : updateTree()
  })
}

//初始化车辆树
function initTree() {
  nextTick(() => {
    ztreeData.ztreeObj = $.fn.zTree.init(
      $("#" + ztreeData.ztreeId),
      Object.assign(ztreeData.ztreeSetting, {
        check: {
          enable: true,
        },
        data: {
          simpleData: {
            enable: true,
            pIdKey: "pid",
          },
        },
        view: {
          showIcon: showIconForTree
        },
      }),
      ztreeData.list
    )
  })
}

//更新车辆树
function updateTree() {
  let nodes = ztreeData.ztreeObj.transformToArray(ztreeData.ztreeObj.getNodes())
  for (var i = 0, l = nodes.length; i < l; i++) {
    if (typeof allVehicleDatas['vehicle_' + nodes[i].id] != 'undefined') {
      nodes[i].name = allVehicleDatas['vehicle_' + nodes[i].id].name;
      nodes[i].iconSkin = "icon" + allVehicleDatas['vehicle_' + nodes[i].id].status;
      ztreeData.ztreeObj.updateNode(nodes[i]);
    }
  }
}

//监听车辆树数据
watch(() => ztreeData.list, (nodes) => {
  console.log('车辆树数据更新', nodes)
  if (ztreeData.ztreeObj) {
    // ztreeData.ztreeObj.destroy();
  }
}, { immediate: true, deep: true })

//车辆树是否显示Icon
function showIconForTree(treeId, treeNode) {
  let arr = ['vehicle', 'fleet', 'route', 'video'];
  return arr.includes(treeNode.type) ? true : false;
}

//递归遍历车辆树
function _rebuildDatas(datas) {
  return datas.forEach(function (row) {
    row.name = _rebuildCarName(row)
    row.open = row.type == 'center' || totalInfo.value.all < 100 ? true : false
    if (row.children) {
      if (row.type == 'vehicle') {
        row.iconSkin = "icon" + row.status
        // row.open = false
        row.checked = _vehicleCheck(row.id)
        allVehicleIds.push(row.id);
        allVehicleDatas['vehicle_' + row.id] = row
      }
      if (row.type == 'fleet') {
        row.iconSkin = 'icon_fleet';
      }
      if (row.type == 'route') {
        row.iconSkin = 'icon_route';
      }
      if (row.type == 'video') {
        row.iconSkin = 'icon_video';
      }

      _rebuildDatas(row.children)
    } else {
      if (row.type == 'vehicle') {
        row.iconSkin = "icon" + row.status
        row.checked = _vehicleCheck(row.id)
        allVehicleIds.push(row.id);
        allVehicleDatas['vehicle_' + row.id] = row
      }
      if (row.type == 'fleet') {
        row.iconSkin = 'icon_fleet';
      }
      if (row.type == 'route') {
        row.iconSkin = 'icon_route';
      }
      if (row.type == 'video') {
        row.iconSkin = 'icon_video';
      }
    }
  })
}

//返回vueX仓库的选中的车辆IDs
const selectedVehicleIds = computed(() => {
  return safeMapStore.selectedVehicleIds
})

//判断车辆是否选中
function _vehicleCheck(id = '') {
  return selectedVehicleIds.value.includes(id)
}

//判断车辆类型
var vehicleTypes = {}
function _vehicleType(key = '') {
  if (JSON.stringify(vehicleTypes) === '{}') {
    basic_vehicle_type.value.forEach((item) => {
      vehicleTypes['key_' + item.value] = item.label
    })
  }
  return vehicleTypes['key_' + key] ? vehicleTypes['key_' + key] : '';
}

//重新遍历车辆名称
function _rebuildCarName(item) {
  let name = '';
  if (item.type == 'vehicle') {
    if (ConfigSetting.value.carShow.includes('车牌')) {
      name += item.name
    }
    if (ConfigSetting.value.carShow.includes('自编号')) {
      name += '(' + item.numbered + ')'
    }
    if (ConfigSetting.value.carShow.includes('车辆类型')) {
      name += '[' + _vehicleType(item.carType) + ']'
    }
    if (ConfigSetting.value.carShow.includes('驾驶员姓名')) {
      name += '  ' + item.driverName
    }
    if (ConfigSetting.value.carShow.includes('速度')) {
      name += '   ' + item.speed + 'km/s'
    }
    if (ConfigSetting.value.carShow.includes('所在区域')) {
      name += '  ' + item.region
    }
    if (ConfigSetting.value.carShow.includes('设备编号')) {
      name += '  （' + item.code + '）'
    }
  } else if (item.type == 'video') {
    name = item.name;
  } else {
    name = item.name + '(' + item.onlineCount + '/' + item.count + ')';
  }
  return name;
}

const contextmenu = ref('')

//车辆树左键单击
function nodeClick(event, treeId, treeNode) {
  // console.log('点击车辆树节点文字')
  if (treeNode.type == 'vehicle' && treeNode.checked == true) {
    safeMapStore.setCurrentSelectVehicleId(treeNode.id)

    //重置窗体和信息状态框的选中为vueX中的默认值
    safeMapStore.setMapCarEjectFlag('status')
    safeMapStore.setMapInfowWindowBtFlag('')

    changeTreeHeight(259) //展示车辆信息框
    safeMapStore.setMapVideoListWidth(0) //隐藏地图右侧视频列表框
  }

  if (treeNode.type == 'vehicle' && treeNode.checked != true) {
    proxy.$modal.msgError('请先勾选该车辆');
    removeCarNodeClickClass()
  }
  contextmenu.value.hide()
}

//移除未经过checkbox选中后就点击节点的选中样式
function removeCarNodeClickClass() {
  let nodes = ztreeData.ztreeObj.getSelectedNodes();
  document.getElementById(nodes[0].tId + '_a').classList.remove('curSelectedNode')
}

//展示当前选中的车辆信息框数据
const currentSelectVehicleData = computed(() => {
  return safeMapStore.currentSelectVehicleData || [];
})

//监听当前选中的车辆被取消时
watch(currentSelectVehicleData, (newValue, oldValue) => {
  if (newValue.length == 0 && !selectedVehicleIds.value.includes(currentSelectVehicleId.value)) {
    safeMapStore.setCurrentSelectVehicleId('')
    changeTreeHeight(32) //隐藏车辆信息框
    removeCarNodeClickClass()
  }
})

//车辆树checkbox选中事件
function checkChange(event, treeId, treeNode) {
  // console.log('点击车辆树节点checkbox框')
  var nodes = ztreeData.ztreeObj.getCheckedNodes(true);
  _getCarIds(nodes)
}

//获取checkbox选中的车辆IDs
function _getCarIds(obj = {}) {
  let carIds = [];
  obj.map((item) => {
    item.type == 'vehicle' ? carIds.push(item.id) : '';
  })
  ztreeData.selectedCarIds = carIds;
  safeMapStore.setSelectedVehicleIds(carIds)
}

//右键节点时 选择的车辆IDs和数据
const rightSelectedCarsIds = ref([]);
const rightSelectedCars = ref([]);

//车辆树右键点击
function nodeContextmenu(event, treeId, treeNode) {
  if (treeNode.type == 'vehicle' || treeNode.type == 'dept' || treeNode.type == 'fleet' || treeNode.type == 'route') {
    ztreeData.rightClickType = treeNode.type

    //右键点击的是车辆就存入节点数据
    if (ztreeData.rightClickType == 'vehicle') {
      ztreeData.rightClickCarData = treeNode
    }
    contextmenu.value.show({ left: event.pageX, top: event.pageY })
  }
  rightSelectedCarsIds.value = [];
  rightSelectedCars.value = [];

  let treeNodesArr = [];
  treeNodesArr.push(treeNode)
  // console.log('车辆树右键点击', treeNodesArr)
  _rightClickSelectedCarsId(treeNodesArr)
}

//收集右键选中的车辆IDs数据
function _rightClickSelectedCarsId(datas) {
  datas.forEach(function (row) {
    if (row.children) {
      if (row.type == 'vehicle') {
        rightSelectedCarsIds.value.push(row.id)
        rightSelectedCars.value.push(row);
      }
      _rightClickSelectedCarsId(row.children)
    } else {
      if (row.type == 'vehicle') {
        rightSelectedCarsIds.value.push(row.id)
        rightSelectedCars.value.push(row);
      }
    }
  })
}

//收藏车辆
function collectVehicle() {
  let params = {
    vehicleIds: rightSelectedCarsIds.value
  }
  addCollectVehicle(params).then(res => {
    proxy.$modal.msgSuccess("收藏成功");
    carsTotal()

    //重新修改车辆节点的收藏状态为取消收藏状态
    updateCarsCollectState(1)
  })
}

//取消收藏车辆
function deleteCollectVehicle() {
  console.log('取消收藏', rightSelectedCarsIds);
  delCollectVehicle(rightSelectedCarsIds.value).then(res => {
    proxy.$modal.msgSuccess("取消收藏成功");
    carsTotal()

    //重新修改车辆节点的收藏状态为收藏状态
    updateCarsCollectState(0)

    if (queryParams.value.status == 4) {
      searchCar()
    }
  })
}

//更新车辆节点的收藏和取消收藏的显示状态
function updateCarsCollectState(status) {
  rightSelectedCars.value.forEach(row => {
    if (rightSelectedCarsIds.value.includes(row.id)) {
      row.collectState = status
      ztreeData.ztreeObj.updateNode(row);
    }
  })
}

function commonContextmenuEvent() {
  //去掉上一个被checkbox选中的车辆节点
  let oldNodes = ztreeData.ztreeObj.getSelectedNodes();
  // console.log('oldNodes', oldNodes)
  if (oldNodes.length > 0) {
    document.getElementById(oldNodes[0].tId + '_a').classList.remove('curSelectedNode')
  }

  //设置当前车辆点名的节点被选中等操作
  let node = ztreeData.rightClickCarData;
  // console.log('当前车辆点名', node)
  ztreeData.ztreeObj.checkNode(node, true, true, true);
  safeMapStore.setCurrentSelectVehicleId(node.id)
  document.getElementById(node.tId + '_a').classList.add('curSelectedNode')
}

//车辆点名
function carRoll() {
  commonContextmenuEvent()
  safeMapStore.setMapCarEjectFlag('roll')
  changeTreeHeight(259) //展示车辆信息框
}

//实时视频
function liveVideo() {
  commonContextmenuEvent()
  safeMapStore.setMapCarEjectFlag('status')
  safeMapStore.setMapVideoListWidth(290)
  safeMapStore.setMapInfowWindowBtFlag('liveVideo')
}

watch(() => JSON.parse(JSON.stringify(queryParams.value)), (newVal, oldVal) => {
  safeMapStore.setCurrentSelectVehicleId('')
  safeMapStore.setSelectedVehicleIds([])
}, { deep: true })

//返回vueX仓库的当前选中的车辆ID
const currentSelectVehicleId = computed(() => {
  return safeMapStore.currentSelectVehicleId
})

//监听当前选中的车辆
watch(currentSelectVehicleId, (value) => {
  var currNode = ztreeData.ztreeObj.getNodeByParam("id", value)
  ztreeData.ztreeObj.selectNode(currNode);
})

//定时更新车辆树数据
var timer = 0;
onMounted(() => {
  timer = setInterval(() => {
    //设置定时器
    searchCar(false); //自定义事件
  }, 60000);
  console.log('carTree onMounted')
})

onUnmounted(() => {
  console.log('carTree onUnmounted')
  clearInterval(timer); //清除定时器
  timer = 0;
})

onActivated(() => {
  // 调用时机为首次挂载
  // 以及每次从缓存中被重新插入时
  console.log('carTree activeted')
  if (timer == 0) {
    timer = setInterval(() => {
      //设置定时器
      searchCar(false); //自定义事件
    }, 60000);
  }
})

onDeactivated(() => {
  // 在从 DOM 上移除、进入缓存
  // 以及组件卸载时调用
  console.log('carTree unactiveted')
  clearInterval(timer); //清除定时器
  timer = 0;
})

</script>

<style lang="scss" scoped>
.tree-container {
  background-color: #091940;
  height: 100%;
  transition: all .3s ease;

  .tree-content {
    display: flex;
    flex-direction: column;
    border-right: 1px solid #4E5A75;
    transition: width .3s ease;

    .tree-search-box {

      .search-li {
        display: flex;
        padding: 10px;
        align-items: center;

        .search-enter {
          width: 100%;
        }

        :deep(.el-input__wrapper) {
          background-color: #11224B;
          box-shadow: 0 0 0 1px #4E5A75;
          padding: 0px 11px
        }

        :deep(.el-input__inner) {
          color: #fff;
          font-size: 12px;
        }

        .search-img {
          margin-left: 15px;
        }
      }

      .search-li:first-child {
        padding-bottom: 8px;
      }

      .search-li:last-child {
        padding-top: 0px;
      }
    }

    .eject-box {
      // transition: width .3s ease;
    }
  }

  .scale-btn {
    position: absolute;
    top: 50%;
    z-index: 999;

    &.scale-open {
      left: 290px;
    }
  }
}
</style>

<style type="scss">
.ztree-box {
  border-top: 1px solid #2B497D;
  border-bottom: 1px solid #2B497D;
  background-color: #091940;
  overflow: scroll;
  flex: 1;
}

.ztree {
  padding: 10px 0;
  font-size: 12px;
}

.vue-giant-tree li {
  list-style-type: none;
  white-space: nowrap;
  outline: none;
}

.vue-giant-tree li ul {
  position: relative;
  padding: 0 0 0 20px;
  margin: 0;
}

.vue-giant-tree .line:before {
  position: absolute;
  top: 0;
  left: 10px;
  height: 100%;
  content: "";
  border-right: 1px dotted #dbdbdb;
}

.vue-giant-tree .roots_docu:before,
.vue-giant-tree .roots_docu:after,
.vue-giant-tree .center_docu:before,
.vue-giant-tree .bottom_docu:before,
.vue-giant-tree .center_docu:after,
.vue-giant-tree .bottom_docu:after {
  position: absolute;
  content: "";
  border: 0 dotted #dbdbdb;
}

.vue-giant-tree .roots_docu:before {
  left: 10px;
  height: 50%;
  top: 50%;
  border-left-width: 1px;
}

.vue-giant-tree .roots_docu:after {
  top: 50%;
  left: 11px;
  width: 50%;
  border-top-width: 1px;
}

.vue-giant-tree .center_docu:before {
  left: 10px;
  height: 100%;
  border-left-width: 1px;
}

.vue-giant-tree .center_docu:after {
  top: 50%;
  left: 11px;
  width: 50%;
  border-top-width: 1px;
}

.vue-giant-tree .bottom_docu:before {
  left: 10px;
  height: 50%;
  border-left-width: 1px;
}

.vue-giant-tree .bottom_docu:after {
  top: 50%;
  left: 11px;
  width: 50%;
  border-top-width: 1px;
}

.vue-giant-tree li a {
  display: inline-block;
  line-height: 18px;
  margin: 0;
  cursor: pointer;
  transition: none;
  vertical-align: middle;
  color: #ffffff;
}

.vue-giant-tree .node_name {
  display: inline-block;
  padding: 1px;
  border-radius: 4px;
}

.vue-giant-tree .curSelectedNode .node_name {
  color: #fff;
  background-color: #668FF5;
}

.vue-giant-tree .curSelectedNode_Edit {
  height: 20px;
  opacity: 0.8;
  color: #000;
  border: 1px #6cc2e8 solid;
  background-color: #9dd6f0;
}

.vue-giant-tree .tmpTargetNode_inner {
  opacity: 0.8;
  color: #fff;
  background-color: #4fcbf0;
  filter: alpha(opacity=80);
}

.vue-giant-tree .rename {
  font-size: 12px;
  line-height: 22px;
  width: 80px;
  height: 22px;
  margin: 0;
  padding: 0;
  vertical-align: top;
  border: 0;
  background: none;
}

.vue-giant-tree .button {
  position: relative;
  display: inline-block;
  line-height: 22px;
  height: 22px;
  width: 22px;
  cursor: pointer;
  text-align: center;
  vertical-align: middle;
}

.vue-giant-tree .button.edit {
  color: #25ae88;
}

.vue-giant-tree .button.remove {
  color: #cb4042;
}

.vue-giant-tree .button.chk {
  position: relative;
  width: 12px;
  height: 12px;
  margin: -5px 5px 0 0;
  border: 1px solid #d7dde4;
  border-radius: 2px;
  background: #1C2F61;
}

.vue-giant-tree .chk.radio_true_full,
.vue-giant-tree .chk.radio_false_full,
.vue-giant-tree .chk.radio_true_full_focus,
.vue-giant-tree .chk.radio_false_full_focus,
.vue-giant-tree .chk.radio_false_disable,
.vue-giant-tree .chk.radio_true_disable,
.vue-giant-tree .chk.radio_true_part,
.vue-giant-tree .chk.radio_false_part,
.vue-giant-tree .chk.radio_true_part_focus,
.vue-giant-tree .chk.radio_false_part_focus {
  border-radius: 8px;
}

.vue-giant-tree .button.chk:after {
  position: absolute;
  top: 1px;
  left: 3px;
  width: 4px;
  height: 7px;
  content: "";
  transition: -webkit-transform 0.2s ease-in-out;
  transition: transform 0.2s ease-in-out;
  transition: transform 0.2s ease-in-out, -webkit-transform 0.2s ease-in-out;
  -webkit-transform: rotate(0deg) scale(0);
  transform: rotate(0deg) scale(0);
  border-right: 2px solid #fff;
  border-bottom: 2px solid #fff;
}

.vue-giant-tree .button.checkbox_false_full_focus {
  border-color: #ccc;
}

.vue-giant-tree .button.checkbox_true_full,
.vue-giant-tree .button.checkbox_true_full_focus,
.vue-giant-tree .button.checkbox_true_part,
.vue-giant-tree .button.checkbox_true_part_focus,
.vue-giant-tree .button.checkbox_true_disable {
  /* border-color: #39f; */
  background-color: #668FF5;
}

.vue-giant-tree .button.checkbox_true_full:after,
.vue-giant-tree .button.checkbox_true_full_focus:after,
.vue-giant-tree .button.checkbox_true_disable:after {
  -webkit-transform: rotate(45deg) scale(1);
  transform: rotate(45deg) scale(1);
}

.vue-giant-tree .button.checkbox_true_part:after,
.vue-giant-tree .button.checkbox_true_part_focus:after {
  top: 4px;
  left: 1px;
  width: 8px;
  height: 1px;
  -webkit-transform: rotate(0deg) scale(1);
  transform: rotate(0deg) scale(1);
  border-right: 0;
}

.vue-giant-tree .button.radio_true_full,
.vue-giant-tree .chk.radio_true_full_focus,
.vue-giant-tree .chk.radio_true_part,
.vue-giant-tree .chk.radio_true_part_focus {
  border-color: #39f;
}

.vue-giant-tree .button.radio_true_full:after,
.vue-giant-tree .chk.radio_true_full_focus:after,
.vue-giant-tree .chk.radio_true_part:after,
.vue-giant-tree .chk.radio_true_part_focus:after {
  top: 3px;
  left: 3px;
  width: 8px;
  -webkit-transform: rotate(0deg) scale(1);
  transform: rotate(0deg) scale(1);
  border: 0;
  border-radius: 4px;
  background: #39f;
}

.vue-giant-tree .button.checkbox_true_disable,
.vue-giant-tree .button.checkbox_false_disable,
.vue-giant-tree .chk.radio_false_disable,
.vue-giant-tree .chk.radio_true_disable {
  cursor: not-allowed;
}

.vue-giant-tree .button.checkbox_false_disable {
  background-color: #f3f3f3;
}

.vue-giant-tree .button.noline_close:before,
.vue-giant-tree .button.noline_open:before,
.vue-giant-tree .button.root_open:before,
.vue-giant-tree .button.root_close:before,
.vue-giant-tree .button.roots_open:before,
.vue-giant-tree .button.roots_close:before,
.vue-giant-tree .button.bottom_open:before,
.vue-giant-tree .button.bottom_close:before,
.vue-giant-tree .button.center_open:before,
.vue-giant-tree .button.center_close:before {
  position: absolute;
  top: 3px;
  left: 10px;
  content: "";
  transition: -webkit-transform ease 0.3s;
  transition: transform ease 0.3s;
  transition: transform ease 0.3s, -webkit-transform ease 0.3s;
  -webkit-transform: rotateZ(0deg);
  transform: rotateZ(0deg);
  -webkit-transform-origin: 25% 50%;
  transform-origin: 25% 50%;
  border: 5px solid;
  border-color: transparent transparent transparent #668FF5;
}

.vue-giant-tree .button.noline_open:before,
.vue-giant-tree .button.root_open:before,
.vue-giant-tree .button.roots_open:before,
.vue-giant-tree .button.bottom_open:before,
.vue-giant-tree .button.center_open:before {
  -webkit-transform: rotateZ(90deg);
  transform: rotateZ(90deg);
}

.vue-giant-tree .button.ico_loading {
  margin-right: 2px;
  background: url("") 0 center no-repeat;
}

.vue-giant-tree .tmpTargetzTree {
  opacity: 0.8;
  background-color: #2ea9df;
  filter: alpha(opacity=80);
}

.vue-giant-tree .tmpzTreeMove_arrow {
  position: absolute;
  width: 18px;
  height: 18px;
  color: #4fcbf0;
}

.ztree li span.button {

  &.icon0_ico_open,
  &.icon0_ico_close,
  &.icon0_ico_docu,
  &.icon1_ico_open,
  &.icon1_ico_close,
  &.icon1_ico_docu {
    background: url(@/assets/images/safety/car_offline_small.png) no-repeat;
    width: 18px;
    height: 14px;
    margin: 0px 4px;
  }

  &.icon2_ico_open,
  &.icon2_ico_close,
  &.icon2_ico_docu {
    background: url(@/assets/images/safety/car_waring_small.png) no-repeat;
    width: 18px;
    height: 14px;
    margin: 0px 4px;
  }

  &.icon3_ico_open,
  &.icon3_ico_close,
  &.icon3_ico_docu {
    background: url(@/assets/images/safety/car_outage_small.png) no-repeat;
    width: 18px;
    height: 14px;
    margin: 0px 4px;
  }

  &.icon4_ico_open,
  &.icon4_ico_close,
  &.icon4_ico_docu {
    background: url(@/assets/images/safety/car_stop_small.png) no-repeat;
    width: 18px;
    height: 14px;
    margin: 0px 4px;
  }

  &.icon5_ico_open,
  &.icon5_ico_close,
  &.icon5_ico_docu {
    background: url(@/assets/images/safety/car_online_small.png) no-repeat;
    width: 18px;
    height: 14px;
    margin: 0px 4px;
  }

  &.icon_fleet_ico_open,
  &.icon_fleet_ico_close,
  &.icon_fleet_ico_docu {
    background: url(@/assets/images/safety/fleet.png) no-repeat;
    width: 14px;
    height: 14px;
    margin: -5px 4px 0;
  }

  &.icon_route_ico_open,
  &.icon_route_ico_close,
  &.icon_route_ico_docu {
    background: url(@/assets/images/safety/route.png) no-repeat;
    width: 18px;
    height: 14px;
    margin: -5px 4px 0;
  }

  &.icon_video_ico_open,
  &.icon_video_ico_close &.icon_video_ico_docu {
    background: url(@/assets/images/safety/video.png) no-repeat;
    width: 18px;
    height: 14px;
    margin: -2px 4px 0;
  }
}
</style>